var http = require('http');
var fs = require('fs');
var path = require('path');
var querystring = require('querystring');
var jsFileMap = new Map();//用来缓存JS文件

//这个程序处理gsgcall的post请求，$0存放着要调用的文件ID名, $1到$10为参数，从磁盘上读取"ID名.js"文件，用eval()去直接运行，
var rootFolder = path.resolve('./'); 
var jsFilesPath = rootFolder + "/target/classes/com/demo/deploy";//相对于当前目录,javascript的存放位置

var app = http.createServer();

app.on('request', function (req, res) { 
    if (req.url === '/gsgcall' && req.method === 'POST') {
        var data = ''; 
        req.on('data', function (chunk) { //同一个post, data事件有可能多次执行，结果要累加
            data += chunk;// chunk 默认是一个二进制数据，和 data拼接会自动 toString
        });

        req.on('end', function () {  
            data = decodeURI(data);  //对url进行解码
            var postBody = querystring.parse(data); //解析为javascript对象
        	var $0 = postBody["$0"];
        	var $1 = postBody["$1"];
        	var $2 = postBody["$2"];
        	var $3 = postBody["$3"];
        	var $4 = postBody["$4"];
        	var $5 = postBody["$5"];
        	var $6 = postBody["$6"];
        	var $7 = postBody["$7"];
        	var $8 = postBody["$8"];
        	var $9 = postBody["$9"];
        	var $10 = postBody["$10"]; 
        	
        	var scriptSourceCode=jsFileMap.get($0);
        	if (scriptSourceCode==undefined || scriptSourceCode==null) { 
        	  scriptSourceCode = fs.readFileSync(jsFilesPath + "/"+$0+".js", "utf-8");
        	  jsFileMap.set($0, scriptSourceCode); 
        	} 
        	var result="";
        	eval(scriptSourceCode);
        	//console.log("result="+result); 
            res.writeHead(200,{"ContentType":"text/html;charset=utf-8"}); 
            res.write(result);
            res.end();
        });
    } 
});

//启动Server
app.listen(8888, function () {
    console.log('GoSqlGo javascript folder:'+jsFilesPath);
    console.log('Node.js Server Started at port 8888');
});

 